package com.ys.service.business.impl;

import com.alibaba.fastjson.JSON;
import com.ys.entity.business.ThrOperateCompanyBrand;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.business.TpShopAnalysisReportForms;
import com.ys.entity.business.TpShopAnalysisReportFormsCount;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.hr.ThrOperateCompanyRoute;
import com.ys.entity.sys.TsOperateOrg;
import com.ys.enume.base.TransactionTypeEnum;
import com.ys.mapper.business.TpShopAnalysisReportFormsCountMapper;
import com.ys.mapper.business.TpShopAnalysisReportFormsDiyMapper;
import com.ys.mapper.business.TpShopAnalysisReportFormsMapper;
import com.ys.service.business.TpShopAnalysisReportFormsService;
import com.ys.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("tpShopAnalysisReportFormsService")
public class TpShopAnalysisReportFormsServiceImpl implements TpShopAnalysisReportFormsService {
	private static final Logger logger = LoggerFactory.getLogger(TpShopAnalysisReportFormsServiceImpl.class);
	@Autowired
	private TpShopAnalysisReportFormsMapper tpShopAnalysisReportFormsMapper;

	@Autowired
	private TpShopAnalysisReportFormsDiyMapper tpShopAnalysisReportFormsDiyMapper;

	@Autowired
	private TpShopAnalysisReportFormsCountMapper tpShopAnalysisReportFormsCountMapper;

	@Override
	public int add(String oldMonth) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar calendar = Calendar.getInstance();
		String thisMonth = oldMonth;
		String oldOldMonth = oldMonth;//上上个月
		Date oldDate = null;
		try {
			oldDate =sdf.parse(oldMonth);
			calendar.setTime(oldDate);
			calendar.add(Calendar.MONTH, +1);//下个月
			thisMonth = sdf.format(calendar.getTime());
			calendar.add(Calendar.MONTH, -2);//上上个月
			oldOldMonth = sdf.format(calendar.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String beginTime = "2023-01";
		if(oldMonth.equals(beginTime)){//2023-06是该功能的上线时间，是最开启统计的时间
			oldOldMonth = "2023-01";
		}
		//查询上上个月是否统计
		List<TpShopAnalysisReportForms> oldOldMonthHasCount = new TpShopAnalysisReportForms()
				.setInfoTime(oldOldMonth)
				//.addLeftJoin("(SELECT MAX( D.InfoTime ) AS InfoTime,D.ShopGuid FROM kjecp_report.dbo.TP_ShopAnalysisReportForms D GROUP BY D.ShopGuid ) AS B ON B.ShopGuid = A.ShopGuid ")
				//.where("A.InfoTime = B.InfoTime")
				.queryList();
		String startTime = "2023-01-01";
		//boolean hasOld = false;//上上个月是否有数据的标识
		if(oldOldMonthHasCount!=null && oldOldMonthHasCount.size()>0){//如果上上个月有数据，累计的开始时间就直接从上上个月开始，不用从2023-01-01开始

			try {
				//Date oldDate1 =sdf.parse(oldOldMonthHasCount.get(0).getInfoTime());
				Calendar calendar1 = Calendar.getInstance();
				calendar1.setTime(oldDate);
				//calendar1.add(Calendar.MONTH, +1);//下个月
				startTime = sdf.format(calendar1.getTime())+"-01";
				if(oldMonth.equals(beginTime)){//2023-06是该功能的上线时间，是最开启统计的时间
					startTime = "2023-01-01";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		String endTime = thisMonth+"-01";
		logger.info("startTime="+startTime+"；endTime="+endTime);
		//统计的月份的天数MonthDay
		int lastDay = new DateUtil().getMonthLastDay(oldMonth);//获取月份的最后一天
		//预付款金额Prepayment(累计)--》按公司
		List<Map<String, Object>> prepaymentList = tpShopAnalysisReportFormsDiyMapper.tpShopAnalysisPrepayment(startTime,endTime);
		//logger.info("预付款金额Prepayment="+prepaymentList);
		//起始报销时间StartSubmitTime(从头开始)--》按公司
		//List<Map<String, Object>> startSubmitTimeList = tShopAnalysisReportFormsDiyMapper.tpShopAnalysisStartSubmitTime(startTime,endTime);
		//累计报销金额TotalSubmitMoney(累计)--》按公司
		List<Map<String, Object>> totalSubmitMoneyList = tpShopAnalysisReportFormsDiyMapper.tpShopAnalysisTotalSubmitMoney(startTime,endTime);
		//logger.info("累计报销金额TotalSubmitMoney="+totalSubmitMoneyList);
		//次月1号资金MonthFirstMoney(一个月)--》按公司
		//List<Map<String, Object>> monthFirstMoneyList = tShopAnalysisReportFormsDiyMapper.tpShopAnalysisMonthFirstMoney(oldMonth+"-"+lastDay);
		List<Map<String, Object>> monthFirstMoneyList = tpShopAnalysisReportFormsDiyMapper.tpShopAnalysisMonthFirstMoney(thisMonth+"-01",thisMonth+"-02");
		//总订单TotalOrder、销售额TotalSale(一个月)--》按店铺
		List<Map<String, Object>> countOrderAndSaleList = tpShopAnalysisReportFormsDiyMapper.tpShopAnalysisCountOrderAndSale(oldMonth+"-01",oldMonth+"-"+lastDay);
		//logger.info("总订单TotalOrder,countOrderAndSaleList="+countOrderAndSaleList);
		//logger.info("startTime11="+oldMonth+"-01"+"；endTime="+oldMonth+"-"+lastDay);
		//亚马逊回款AmazonBack、头程运费FirstLegCost、仓储费StorageCost(一个月)--》按公司
		List<Map<String, Object>> amazonBackAndFirstLegCostList = tpShopAnalysisReportFormsDiyMapper.tpShopAnalysisAmazonBackAndFirstLegCost(oldMonth+"-01",endTime);
		//管理绩效MeritsManage(一个月)--》按公司
		List<Map<String, Object>> meritsManageList = tpShopAnalysisReportFormsDiyMapper.tpShopAnalysisMeritsManage();
		//采购成本ProcureCost(一个月)--》按公司
		List<Map<String, Object>> procureCostList = tpShopAnalysisReportFormsDiyMapper.tpShopAnalysisProcureCost(oldMonth+"-01",endTime);
		//快递运费FastMailCost、物流运费LogisticsCost(一个月)--》按店铺
		List<Map<String, Object>> fastMailAndLogisticsList = tpShopAnalysisReportFormsDiyMapper.tpShopAnalysisFastMailAndLogistics(oldMonth+"-01",endTime);
		//包装费PackCost(一个月)--》按公司
		List<Map<String, Object>> packCostList = tpShopAnalysisReportFormsDiyMapper.tpShopAnalysisPackCost(oldMonth+"-01",endTime);
		//管理绩效MeritsAllocation(一个月)--》按公司
		List<Map<String, Object>> meritsAllocationList = tpShopAnalysisReportFormsDiyMapper.tpShopAnalysisMeritsAllocation(oldMonth+"-01",endTime);

		//回本时间RecoveryTime、回本周期RecoveryCycle(从头开始)--》按公司
		//List<Map<String, Object>> recoveryList = tShopAnalysisReportFormsDiyMapper.tpShopAnalysisTotalSubmitMoneyList(startTime,endTime,"");

		//运营机构列表
		//List<ThrOperateCompanyRoute> routeList = new ThrOperateCompanyRoute().queryList();
		List<TsOperateOrg> routeList = new TsOperateOrg().queryList();
		//运营公司表信息
		List<ThrOperateCompanyApply> companyList = new ThrOperateCompanyApply().queryList();

		//获取所有的店铺信息
		List<Map<String, Object>> shopList = new TpAmazonShop()
				.addField("UC.UserId AS cUser")
				.addField("UC.DeptId AS cDept")
				.addField("S.VGsBm AS companyID")
				.addLeftJoin("kjecp.dbo.TP_AmazonSeller S ON S.id = A.amazonSellerId")
				.addLeftJoin("kjecp.dbo.THR_OperateCompanyApply B ON S.VGsBm = B.VGsBm")
				.addLeftJoin("kjecp.dbo.TS_UserChange UC ON B.OperatorChangeId = UC.Id")
				//.addLeftJoin("kjecp.dbo.TS_UserInfo U ON UC.UserId = U.UserId")
				.where("S.VGsBm IS NOT NULL")

				.setOrderby("S.VGsBm ASC ")
				.queryMap();
		if(shopList!=null && shopList.size()>0){
            List<TpShopAnalysisReportForms> addList = new ArrayList<>();
			//List<TpShopAnalysisReportForms> hasList = new TpShopAnalysisReportForms().setInfoTime(oldMonth).queryList();
			for(Map<String, Object> shopItem:shopList){
				TpShopAnalysisReportForms entity = new TpShopAnalysisReportForms();//新增参数
				entity.setStatus(1);//状态
				entity.setMonthDay(lastDay);//统计的月份的天数
				entity.setInfoTime(oldMonth);//统计的时间
				String shopGuid = shopItem.get("guid").toString();//店铺guid
				String shopId = shopItem.get("id").toString();//店铺id
				String companyGuid = shopItem.get("companyID").toString();//公司bm
				entity.setShopGuid(shopGuid);
				entity.setCompanyGuid(companyGuid);
				entity.setUserId(shopItem.get("cUser")!=null?shopItem.get("cUser").toString():null);//运营人id
				entity.setDeptId(shopItem.get("cDept")!=null?shopItem.get("cDept").toString():null);//运营人组别
				BigDecimal numPrepayment = new BigDecimal(0);//预付款金额
				BigDecimal numTotalSubmitMoney = new BigDecimal(0);//累计报销金额
				Date startSubmitTime = null;//起始报销时间
				Date recoveryTime = null;//回本时间
				int recoveryCycle = 0;//回本周期
				//获取上上个月的统计数据
				if(oldOldMonthHasCount!=null && oldOldMonthHasCount.size()>0){
					List<TpShopAnalysisReportForms> oldInfo = oldOldMonthHasCount.stream().filter(item->item.getShopGuid().equals(shopGuid)).collect(Collectors.toList());
					if(oldInfo.size()>0){
						numPrepayment = oldInfo.get(0).getPrepayment();
						numTotalSubmitMoney = oldInfo.get(0).getTotalSubmitMoney();
						startSubmitTime = oldInfo.get(0).getStartSubmitTime();
						recoveryTime = oldInfo.get(0).getRecoveryTime();
						recoveryCycle = oldInfo.get(0).getRecoveryCycle()==null?0:oldInfo.get(0).getRecoveryCycle();
					}
				}

				//预付款金额--》按公司
				if(prepaymentList!=null && prepaymentList.size()>0){
					List<Map<String, Object>> dataInfo1 = prepaymentList.stream().filter(item->item.get("VGsBm").toString().equals(companyGuid)).collect(Collectors.toList());
					if(dataInfo1.size()>0) numPrepayment = numPrepayment.add((BigDecimal)dataInfo1.get(0).get("prepayment"));
				}
				//累计报销金额--》按公司
				//设X值=（运营服务→费用划拨）之和+（运营服务→运营服务费）之和+（运营服务→预付款退回）+（经营费用→工资）之和+（经营费用→五险一金）之和+（运营服务→办公场地费）之和
				//X为正值时，累计报销金额 = 上个月累计报销金额；预付金额 = 上个月预付金额 + 当月预付金额 + 当月累计报销金额
				//X为负值时，累计报销金额 = 上个月累计报销金额 + 当月累计报销金额；预付金额 = 上个月预付金额 + 当月预付金额
				if(totalSubmitMoneyList!=null && totalSubmitMoneyList.size()>0){
					List<Map<String, Object>> dataInfo = totalSubmitMoneyList.stream().filter(item->item.get("VGsBm").toString().equals(companyGuid)).collect(Collectors.toList());
					if(dataInfo.size()>0){
						BigDecimal dataTotalSubmitMoney = (BigDecimal)dataInfo.get(0).get("totalSubmitMoney");
						if(dataTotalSubmitMoney.compareTo(BigDecimal.ZERO)>0){
							numPrepayment.add(dataTotalSubmitMoney);
						}else {
							//记录累计
							if(dataInfo.size()>0) numTotalSubmitMoney = numTotalSubmitMoney.add(dataTotalSubmitMoney);//.add(numPrepayment);
						}
						//起始报销时间--》按公司
						if(startSubmitTime==null && numTotalSubmitMoney.compareTo(BigDecimal.ZERO)>0){
							startSubmitTime = oldDate;
						}
						BigDecimal fNumTotalSubmitMoney = BigDecimal.ZERO.subtract(numTotalSubmitMoney);//累计金额取反
						//获取回本时间、回本周期
						if(recoveryTime == null && fNumTotalSubmitMoney.compareTo(numPrepayment)>0){
							recoveryTime = oldDate;//回本时间
							//entity.setRecoveryCycle(recoveryCycle);//回本周期
						}
					}
				}
				entity.setTotalSubmitMoney(numTotalSubmitMoney);//累计报销金额
				entity.setPrepayment(numPrepayment);//预付款金额
				entity.setStartSubmitTime(startSubmitTime);//起始报销时间
				entity.setRecoveryTime(recoveryTime);//回本时间
				entity.setRecoveryCycle(recoveryCycle);//回本周期

				//次月1号资金MonthFirstMoney--》按公司
				BigDecimal monthFirstMoney = new BigDecimal(0);
				if(monthFirstMoneyList!=null && monthFirstMoneyList.size()>0){
					List<Map<String, Object>> dataInfo = monthFirstMoneyList.stream().filter(item->item.get("VGsBm").toString().equals(companyGuid)).collect(Collectors.toList());
					if(dataInfo.size()>0) monthFirstMoney = (BigDecimal)dataInfo.get(0).get("FJe");
				}
				entity.setMonthFirstMoney(monthFirstMoney);
				//总订单TotalOrder、销售额TotalSale(一个月)--》按店铺
				int totalOrder = 0;
				BigDecimal totalSale = new BigDecimal(0);
				if(countOrderAndSaleList!=null && countOrderAndSaleList.size()>0){
					List<Map<String, Object>> dataInfo = countOrderAndSaleList.stream().filter(item->item.get("ShopId").toString().equals(shopId)).collect(Collectors.toList());
					if(dataInfo.size()>0){
						totalOrder = Integer.parseInt(dataInfo.get(0).get("totalOrder").toString());
						totalSale = (BigDecimal)dataInfo.get(0).get("totalSale");
					}
				}
				entity.setTotalOrder(totalOrder);
				entity.setTotalSale(totalSale);

				//亚马逊回款AmazonBack、头程运费FirstLegCost、仓储费StorageCost(一个月)--》按公司
				BigDecimal amazonBack = new BigDecimal(0);
				BigDecimal firstLegCost = new BigDecimal(0);
				BigDecimal storageCost = new BigDecimal(0);
				if(amazonBackAndFirstLegCostList!=null && amazonBackAndFirstLegCostList.size()>0){
					List<Map<String, Object>> dataInfo = amazonBackAndFirstLegCostList.stream()
							.filter(item->item.get("VGsBm").toString().equals(companyGuid) && item.get("VJyLx").toString().equals( TransactionTypeEnum.BusinessType.TP_ShopAnalysisReportForms_YY.name))
							.collect(Collectors.toList());//过滤亚马逊回款
					if(dataInfo.size()>0) amazonBack = (BigDecimal)dataInfo.get(0).get("cost");

					List<Map<String, Object>> firstLegInfo = amazonBackAndFirstLegCostList.stream()
							.filter(item->item.get("VGsBm").toString().equals(companyGuid) && item.get("VJyLx").toString().equals(TransactionTypeEnum.BusinessType.TP_ShopAnalysisReportForms_WL.name))
							.collect(Collectors.toList());//过滤头程运费
					if(firstLegInfo.size()>0) firstLegCost = (BigDecimal)firstLegInfo.get(0).get("cost");

					List<Map<String, Object>> storageCostInfo = amazonBackAndFirstLegCostList.stream()
							.filter(item->item.get("VGsBm").toString().equals(companyGuid) && item.get("VJyLx").toString().equals(TransactionTypeEnum.BusinessType.TP_ShopAnalysisReportForms_CC.name))
							.collect(Collectors.toList());//过滤仓储费
					if(storageCostInfo.size()>0) storageCost = (BigDecimal)storageCostInfo.get(0).get("cost");
				}
				entity.setAmazonBack(amazonBack);
				entity.setFirstLegCost(firstLegCost);
				entity.setStorageCost(storageCost);

				//管理绩效MeritsManage(一个月)--》按公司
				BigDecimal meritsManage = new BigDecimal(0);
				if(meritsManageList!=null && meritsManageList.size()>0){
					List<Map<String, Object>> dataInfo = meritsManageList.stream().filter(item->item.get("VGsBm")!=null && item.get("VGsBm").toString().equals(companyGuid)).collect(Collectors.toList());
					if(dataInfo.size()>0) meritsManage = (BigDecimal)dataInfo.get(0).get("vJcBl");
				}
				entity.setMeritsManage(meritsManage);

				//采购成本ProcureCost(一个月)--》按公司 procureCostList
				BigDecimal procureCost = new BigDecimal(0);
				if(procureCostList!=null && procureCostList.size()>0){
					List<Map<String, Object>> dataInfo = procureCostList.stream().filter(item->item.get("VGsBm")!=null && item.get("VGsBm").toString().equals(companyGuid)).collect(Collectors.toList());
					if(dataInfo.size()>0) procureCost = (BigDecimal)dataInfo.get(0).get("procureCost");
				}
				entity.setProcureCost(procureCost);

				//快递运费FastMailCost、物流运费LogisticsCost(一个月)--》按店铺 fastMailAndLogisticsList
				BigDecimal fastMailCost = new BigDecimal(0);
				BigDecimal logisticsCost = new BigDecimal(0);
				if(fastMailAndLogisticsList!=null && fastMailAndLogisticsList.size()>0){
					List<Map<String, Object>> fastMailCostInfo = fastMailAndLogisticsList.stream()
							.filter(item->item.get("Id").toString().equals(shopId) && item.get("logisticsType").toString().equals("快递"))
							.collect(Collectors.toList());//过滤快递
					if(fastMailCostInfo.size()>0) fastMailCost = (BigDecimal)fastMailCostInfo.get(0).get("cost");

					List<Map<String, Object>> logisticsCostInfo = fastMailAndLogisticsList.stream()
							.filter(item->item.get("Id").toString().equals(shopId) && item.get("logisticsType").toString().equals("物流"))
							.collect(Collectors.toList());//过滤物流
					if(logisticsCostInfo.size()>0) logisticsCost = (BigDecimal)logisticsCostInfo.get(0).get("cost");
				}
				entity.setFastMailCost(fastMailCost);
				entity.setLogisticsCost(logisticsCost);

				//包装费PackCost(一个月)--》按公司 packCostList
				BigDecimal packCost = new BigDecimal(0);
				if(packCostList!=null && packCostList.size()>0){
					List<Map<String, Object>> dataInfo = packCostList.stream().filter(item->item.get("VGsBm").toString().equals(companyGuid)).collect(Collectors.toList());
					if(dataInfo.size()>0) packCost = (BigDecimal)dataInfo.get(0).get("packCost");
				}
				entity.setPackCost(packCost);


				//管理绩效MeritsAllocation(一个月)--》按公司 meritsAllocationList
				BigDecimal meritsAllocation = new BigDecimal(0);
				if(meritsAllocationList!=null && meritsAllocationList.size()>0){
					List<Map<String, Object>> dataInfo = meritsAllocationList.stream().filter(item->item.get("VGsBm").toString().equals(companyGuid)).collect(Collectors.toList());
					if(dataInfo.size()>0) meritsAllocation = (BigDecimal)dataInfo.get(0).get("cost");
				}
				entity.setMeritsAllocation(meritsAllocation);

				//运营机构相关参数
				List<ThrOperateCompanyApply> companyListByBm = companyList.stream().filter(item->item.getVgsbm()!=null && item.getVgsbm().equals(companyGuid)).collect(Collectors.toList());
				if(companyListByBm.size()>0 && companyListByBm.get(0).getOperateOrgId()!=null){
					List<TsOperateOrg> routeListByBm = routeList.stream()
							.filter(item->item.getId().equals(companyListByBm.get(0).getOperateOrgId())).collect(Collectors.toList());
					if(routeListByBm.size()>0){
						String orgName = routeListByBm.get(0).getName();//运营机构
						if(orgName!=null && !orgName.equals("")){
							entity.setOrgName(orgName);
						}
					/*
					String orgNameBelong = getBelongOrgName(routeList,routeListByBm.get(0));//所属运营机构
					if(orgNameBelong!=null && !orgNameBelong.equals("")){
						entity.setOrgNameBelong(orgNameBelong);
					}
					 */
					}
				}



				/*
				if(hasList!=null && hasList.size()>0){
					List<TpShopAnalysisReportForms> hasListByShop = hasList.stream().filter(item->item.getShopGuid().equals(shopGuid)).collect(Collectors.toList());
					if(hasListByShop.size()>0){
						entity.setId(hasListByShop.get(0).getId());
						//修改
						tpShopAnalysisReportFormsMapper.update(entity);
					}else {
						//新增
						tpShopAnalysisReportFormsMapper.insert(entity);
					}
				}else {
					//新增
					tpShopAnalysisReportFormsMapper.insert(entity);
				}
				 */
                addList.add(entity);
			}

            if(addList!=null && addList.size()>0){
                tpShopAnalysisReportFormsDiyMapper.deleteAnalysisReportFormsByInfoTime(oldMonth);//删除
                int count = 50;
                for(int i=0;i<addList.size()+count;i=i+count){
                    List<TpShopAnalysisReportForms> newlist = addList.stream().skip(i).limit(count).collect(Collectors.toList());
                    tpShopAnalysisReportFormsDiyMapper.insertAnalysisReportFormsByList(newlist);//批量新增
                }
            }


		}
		return 1;
	}

	/**
	 * 递归获取所属的运营机构名称
	 * @paramrouteList 所有运营机构信息
	 * @paramrouteInfoByBm 当前运营机构信息
	 * @return 运营机构名称

	public String getBelongOrgName(List<ThrOperateCompanyRoute> routeList ,ThrOperateCompanyRoute routeInfoByBm){
		String orgNameBelong = null;
		String vGsBm = routeInfoByBm.getVGsBm();
		String routeCode = routeInfoByBm.getRouteCode();
		if(routeCode ==null || routeCode.equals("")){
			return orgNameBelong;
		}
		String[] routeCodes = routeCode.split(".");
		if(routeCodes.length>1){
			String upVGsBm = null;
			for(int i=routeCodes.length-1;i>=0;i--){
				if(routeCodes[i].equals(vGsBm) && i-1>=0){
					upVGsBm = routeCodes[i-1];//上级运营机构
				}
			}
			String upVGsBms = upVGsBm;
			if(upVGsBms!=null){
				//获取上级的运营机构信息
				List<ThrOperateCompanyRoute> routeListUp = routeList.stream()
						.filter(item->item.getVGsBm().equals(upVGsBms))
						.collect(Collectors.toList());
				if(routeListUp.size()>0){
					String orgName = routeListUp.get(0).getOrgName();
					if(orgName!=null && !orgName.equals("")){
						orgNameBelong = orgName;
					}else {//如果为空，则继续往上级查询
						orgNameBelong = getBelongOrgName(routeList,routeListUp.get(0));
					}
				}
			}
		}
		return orgNameBelong;
	}
	 */
	@Override
	public int addData(TpShopAnalysisReportForms entity) {
		return tpShopAnalysisReportFormsMapper.insert(entity);
	}

	/**
	 * 获取回本时间、回本周期
	 * @param recoveryList 所有数据
	 * @param companyGuid 公司guid
	 * @return
	 */
	public Map<String,Object> getRecoveryNew(String companyGuid,String oldMonth,List<Map<String, Object>> recoveryList){
		Map<String,Object> result = new HashMap<>();
		List<Map<String, Object>> totalSubmitMoneyList = recoveryList.stream()
				.filter(item->(item.get("companyId")!=null?item.get("companyId").toString():"").equals(companyGuid)).collect(Collectors.toList());
		Date recoveryTime = null;
		int recoveryCycle = 0;
		if(totalSubmitMoneyList!=null && totalSubmitMoneyList.size()>0){
			float count = 0;
			for( Map<String, Object> item: totalSubmitMoneyList ){
				if(item.get("infoType").toString().equals("1")){//累计报销金额
					count = count - Float.parseFloat(item.get("money").toString());
				}else {//预付款金额
					count = count - Float.parseFloat(item.get("money").toString());
				}
				if(count>0){
					recoveryTime = (Date) item.get("thisTime");
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
					try {
						Date oldDate = sdf.parse(oldMonth);
						long startTimeNum = recoveryTime.getTime();
						long endTimeNum = oldDate.getTime();
						long betweenDays = (endTimeNum - startTimeNum) / (1000 * 3600 * 24);
						//开始时间和结束时间相差的天数
						recoveryCycle = Integer.parseInt(String.valueOf(betweenDays));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			}
		}
		result.put("recoveryTime",recoveryTime);
		result.put("recoveryCycle",recoveryCycle);
		return result;
	}


	/**
	 * 获取回本时间、回本周期
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @param companyGuid 公司guid
	 * @return

	public Map<String,Object> getRecovery(String startTime,String endTime,String companyGuid,String oldMonth){
		Map<String,Object> result = new HashMap<>();
		//回本时间RecoveryTime、回本周期RecoveryCycle(从头开始)--》按公司
		//累计报销金额列表、预付款金额列表
		List<Map<String, Object>> totalSubmitMoneyList = tShopAnalysisReportFormsDiyMapper.tpShopAnalysisTotalSubmitMoneyList(startTime,endTime,companyGuid);
		Date recoveryTime = null;
		int recoveryCycle = 0;
		if(totalSubmitMoneyList!=null && totalSubmitMoneyList.size()>0){
			float count = 0;
			for( Map<String, Object> item: totalSubmitMoneyList ){
				if(item.get("infoType").toString().equals("1")){//累计报销金额
					count = count + Float.parseFloat(item.get("money").toString());
				}else {//预付款金额
					count = count - Float.parseFloat(item.get("money").toString());
				}
				if(count>0){
					recoveryTime = (Date) item.get("thisTime");
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
					try {
						Date oldDate = sdf.parse(oldMonth);
						long startTimeNum = recoveryTime.getTime();
						long endTimeNum = oldDate.getTime();
						long betweenDays = (endTimeNum - startTimeNum) / (1000 * 3600 * 24);
						//开始时间和结束时间相差的天数
						recoveryCycle = Integer.parseInt(String.valueOf(betweenDays));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			}
		}
		result.put("recoveryTime",recoveryTime);
		result.put("recoveryCycle",recoveryCycle);
		return result;
	} */

	/**
	 * 根据按店铺、公司、用户，获取相应月份的统计数据
	 */
	@Override
	public TpShopAnalysisReportForms getOldMonthInfo(String infoTime,String shopGuid,String companyId,String userId,int pageType,String deptId,String orgName) {
		TpShopAnalysisReportForms oldmonthInfo = null;

		if(pageType == 0){//按店铺
			oldmonthInfo = new TpShopAnalysisReportForms()
					.setInfoTime(infoTime)
					.setShopGuid(shopGuid)
					.queryFirst();
		}
		else if(pageType == 4){//按总计
			TpShopAnalysisReportFormsCount tpShopAnalysisReportFormsCount = new TpShopAnalysisReportFormsCount()
					.setInfoTime(infoTime)
					.queryFirst();
			if(tpShopAnalysisReportFormsCount!=null){
				oldmonthInfo = JSON.parseObject(JSON.toJSONString(tpShopAnalysisReportFormsCount), TpShopAnalysisReportForms.class);
			}
		}
		else {
			List<Map<String, Object>> infoList = null;
			if(pageType == 1){//按公司
				infoList = tpShopAnalysisReportFormsDiyMapper.shopAnalysisReportFormsByCompanyAndMonth(infoTime,companyId);
			}else {//按组别
				infoList = tpShopAnalysisReportFormsDiyMapper.shopAnalysisReportFormsByOrgNameAndMonth(infoTime,orgName);
			}
			if(infoList!=null && infoList.size()>0){
				Map<String, Object> dateInfo = infoList.get(0);
				oldmonthInfo = JSON.parseObject(JSON.toJSONString(dateInfo), TpShopAnalysisReportForms.class);
				/*
				oldmonthInfo.setTotalOrder(dateInfo.get("TotalOrder")!=null?(int)dateInfo.get("TotalOrder"):0);
				oldmonthInfo.setTotalSale((BigDecimal)dateInfo.get("TotalSale"));
				oldmonthInfo.setLogisticsCost((BigDecimal)dateInfo.get("LogisticsCost"));
				oldmonthInfo.setFastMailCost((BigDecimal)dateInfo.get("FastMailCost"));
				oldmonthInfo.setPrepayment((BigDecimal)dateInfo.get("Prepayment"));
				oldmonthInfo.setTotalSubmitMoney((BigDecimal)dateInfo.get("TotalSubmitMoney"));
				oldmonthInfo.setMonthFirstMoney((BigDecimal)dateInfo.get("MonthFirstMoney"));
				oldmonthInfo.setAmazonBack((BigDecimal)dateInfo.get("AmazonBack"));
				oldmonthInfo.setMeritsManage((BigDecimal)dateInfo.get("MeritsManage"));
				oldmonthInfo.setProcureCost((BigDecimal)dateInfo.get("ProcureCost"));
				oldmonthInfo.setFirstLegCost((BigDecimal)dateInfo.get("FirstLegCost"));
				oldmonthInfo.setStorageCost((BigDecimal)dateInfo.get("StorageCost"));
				oldmonthInfo.setPackCost((BigDecimal)dateInfo.get("PackCost"));
				oldmonthInfo.setStartSubmitTime((Date) dateInfo.get("StartSubmitTime"));
				oldmonthInfo.setMonthDay((int)dateInfo.get("MonthDay"));
				oldmonthInfo.setMeritsAllocation((BigDecimal)dateInfo.get("MeritsAllocation"));

				 */
			}else {
				return null;
			}
		}
		return oldmonthInfo;
	}

	@Override
	public int delByInfoTime(String infoTime) {
		return tpShopAnalysisReportFormsDiyMapper.deleteShopAnalysisReportFormsByTime(infoTime);
	}

	/**
	 * 根据按用户，获取相应月份的统计数据
	 */
	@Override
	public Map<String, Object> getAnalysisReportFormsInfoByDept(String infoTime,String deptId) {
		Map<String, Object> resultInfo = new HashMap<>();
		List<Map<String, Object>> infoList = tpShopAnalysisReportFormsDiyMapper.shopAnalysisReportFormsByUserTableDate(infoTime,deptId);
		if(infoList!=null && infoList.size()>0){
			Map<String, Object> dateInfo = infoList.get(0);
			resultInfo.put("totalOrder",(int)dateInfo.get("totalOrder"));
			resultInfo.put("totalSale",(BigDecimal)dateInfo.get("totalSale"));
			resultInfo.put("logisticsCost",(BigDecimal)dateInfo.get("logisticsCost"));
			resultInfo.put("fastMailCost",(BigDecimal)dateInfo.get("fastMailCost"));
			resultInfo.put("prepayment",(BigDecimal)dateInfo.get("prepayment"));
			resultInfo.put("totalSubmitMoney",(BigDecimal)dateInfo.get("totalSubmitMoney"));
			resultInfo.put("monthFirstMoney",(BigDecimal)dateInfo.get("monthFirstMoney"));
			resultInfo.put("amazonBack",(BigDecimal)dateInfo.get("amazonBack"));
			resultInfo.put("meritsManage",(BigDecimal)dateInfo.get("meritsManage"));
			resultInfo.put("procureCost",(BigDecimal)dateInfo.get("procureCost"));
			resultInfo.put("firstLegCost",(BigDecimal)dateInfo.get("firstLegCost"));
			resultInfo.put("storageCost",(BigDecimal)dateInfo.get("storageCost"));
			resultInfo.put("packCost",(BigDecimal)dateInfo.get("packCost"));
			resultInfo.put("startSubmitTime",(Date) dateInfo.get("startSubmitTime"));
			resultInfo.put("monthDay",(int)dateInfo.get("monthDay"));
			resultInfo.put("meritsAllocation",(BigDecimal)dateInfo.get("meritsAllocation"));
			resultInfo.put("operateUser",dateInfo.get("operateUser"));
			resultInfo.put("vYyJb",dateInfo.get("vYyJb"));
			resultInfo.put("vGsJc",dateInfo.get("vGsJc"));
			resultInfo.put("infoTime",infoTime);
			resultInfo.put("deptId",deptId);
			resultInfo.put("userId",dateInfo.get("userId"));
			resultInfo.put("userWork",dateInfo.get("userWork"));
		}else {
			return null;
		}
		return resultInfo;
	}

	@Override
	public int editData(TpShopAnalysisReportForms entity) {
		return tpShopAnalysisReportFormsMapper.update(entity);
	}


	@Override
	public int addTotal(String oldMonth) {
		int result = 0;
		List<Map<String, Object>> totalList = tpShopAnalysisReportFormsDiyMapper.shopAnalysisReportFormsByTotal(oldMonth);
		if(totalList!=null && totalList.size()>0){
			TpShopAnalysisReportFormsCount entity = JSON.parseObject(JSON.toJSONString(totalList.get(0)), TpShopAnalysisReportFormsCount.class);
			entity.setInfoTime(oldMonth);
			entity.setStatus(1);
            tpShopAnalysisReportFormsDiyMapper.deleteAnalysisReportFormsCountByInfoTime(oldMonth);
			result = tpShopAnalysisReportFormsCountMapper.insert(entity);
		}
		return result;
	}

}
